<template>
	<div class="app-container">
		<div class="flex-export-data">
			<el-button v-if="status !== 2" type="primary" :disabled="status === 3" @click="handleExport">
				{{ status !== 3 ? "导出" : "等待中" }}
			</el-button>
			<el-col v-if="status === 2" :span="8" class="fr ml-20" align="right">
				<el-progress :percentage="percentage" class="el-progress" />
			</el-col>
			<el-button v-if="status !== 1" class="ml-20" @click="taskDel"> 取消 </el-button>
			<el-button v-show="status === 1 && downLoadPath !== ''" type="info" @click="handleDownLoad">
				下载数据
			</el-button>
		</div>
	</div>
</template>
<script lang="ts" setup>
import { ElNotification } from 'element-plus'
import { ref, onBeforeUnmount } from 'vue'
import { taskRate, taskDel as del, taskCreate } from './restful'
type TaskOption = {
	param: object;
};
const props = defineProps({
	taskName: String,
	taskOption: Object as () => TaskOption
})
const downLoadPath = ref('')
const percentage = ref(0)
const task_id = ref(0)
const time = ref(0)
const status = ref(1)

onBeforeUnmount(() => {
	// 离开页面，销毁定时器
	clearTimeout(time.value)
})

// 导出
const handleExport = () => {
	taskMissionCreate()
}

// 导出任务查询 定时器，3s一查询
const taskRateInquiry = async () => {
	const param = {
		task_name: props.taskName,
		task_id: task_id.value,
		...props.taskOption?.param
	}
	const res: any = await taskRate(param)
	const data = res.data
	status.value = data.status
	if (data.status === 1) {
		// 导出完成
		if (data.completed.path) {
			// 有导出数据的时候
			downLoadPath.value = import.meta.env.VITE_APP_AUTH_API + data.completed.path
		}
		if (time.value !== 0) {
			ElNotification({
				title: '温馨提示',
				message: '导出完成！',
				type: 'success'
			})
		}
	} else {
		if (data.status === 2) {
			percentage.value = parseFloat(data.processing.rate)
			task_id.value = data.processing.task_id
		} else if (data.status === 3) {
			// 处于导出等待状态
			percentage.value = 0
			task_id.value = data.waiting.task_id
		}
		time.value = window.setTimeout(taskRateInquiry, 3000)
	}
}

// 导出任务删除
const taskDel = async () => {
	const param = {
		task_id: task_id.value
	}
	await del(param)
	ElNotification({
		title: '温馨提示',
		message: '导出任务取消成功！',
		type: 'success'
	})
	clearTimeout(time.value)
	// 查询导出状态
	taskRateInquiry()
}

// 导出任务创建
const taskMissionCreate = async () => {
	const param = {
		task_name: props.taskName,
		...props.taskOption?.param
	}
	const res: any = await taskCreate(param)
	task_id.value = res.data.task_id
	taskRateInquiry() // 导出任务创建完成，开始执行轮询任务查询导出进度
}

// 下载数据
const handleDownLoad = () => {
	const a = document.createElement('a')
	a.href = downLoadPath.value
	a.download = 'exportData'
	a.click()
}
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
